package com.hk.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hk.app.utils.RedisCilent;
import com.hk.commons.CacheConstants;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;

public class ValidityInterceptor implements HandlerInterceptor {
	protected Logger logger = LoggerFactory
			.getLogger(this.getClass().getName());

	private String[] allowUrls;

	@Override
	public boolean preHandle(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse, Object paramObject)
			throws Exception {
		paramHttpServletResponse.setCharacterEncoding("UTF-8");
		String currentUrl = paramHttpServletRequest.getRequestURL().toString();
		// logger.info("请求的url={}", currentUrl);

		// 不用校验允许通过
		if (allowUrls != null && allowUrls.length != 0) {// 拦截 TODO
			for (int i = 0; i < allowUrls.length; i++) {
				if (currentUrl.toString().indexOf(allowUrls[i]) != -1) {
					// logger.info("preHandleNeedToControll[" + currentUrl +
					// "]");
					return true;
				}
			}
		}

		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> map = new HashMap<String, String>();

		String version = paramHttpServletRequest.getParameter("v");
		String token = paramHttpServletRequest.getParameter("token");
		String userId = paramHttpServletRequest.getParameter("userId");
		String finanlcial = paramHttpServletRequest.getParameter("finanlcial");
		if (StringUtils.isNotEmpty(version) && StringUtils.isNotEmpty(token)) {
			// 版本小于1.7系统不做验证与提人处理　后续版本更新后，删除此项控制
			version = version.substring(0, 3);
			if (Double.parseDouble(version) < 1.6) {
				return true;
			}
			if (StringHelper.isNotEmpty(finanlcial)) {// 理财师版登陆
				boolean t = false;
				if (RedisCilent.existsKey(CacheConstants.FINALCIAL_LOG_TOKEN
						+ userId)) {
					String cacheToken = RedisCilent
							.getString(CacheConstants.FINALCIAL_LOG_TOKEN
									+ userId);
					if (token.equals(cacheToken)) {
						t = true;
					}
				}
				if (t) {
					return true;
				} else {
					logger.info("理财师版拦截token不存在", token);
					map.put("result", "token is null.");
					map.put("resultCode", ResultCode.ILLEGAL_TOKEN.getCode());
					paramHttpServletResponse.getWriter().print(
							mapper.writeValueAsString(map));
					return false;
				}
			} else {
				
				if (RedisCilent
						.existsKey(CacheConstants.UserLog_Token + userId)) {
					
					String cacheToken = RedisCilent
							.getString(CacheConstants.UserLog_Token + userId);
					if (token.equals(cacheToken)) {
						 
						return true;
					}else{
						logger.info("token 存在，但不相等 token={}", token);
					}
				}else{
					logger.info("token 不 存在 token={}", token);
				}
 
				map.put("result", "token is null.");
				map.put("resultCode", ResultCode.ILLEGAL_TOKEN.getCode());
				paramHttpServletResponse.getWriter().print(
						mapper.writeValueAsString(map));
				return false;
				 
			}

		} else {
			return true;
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse, Object paramObject,
			Exception paramException) throws Exception {
		// TODO Auto-generated method stub

	}

	public String[] getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

}
